import React, { useState } from "react";
import { Button, Form, Input, Toast } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { request } from "../axios/request";
import { setLoginStatus } from "../utils/auth";
import "./login.css";

function Index() {
  const [form] = Form.useForm();
  const [countdown, setCountdown] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const navigate = useNavigate();

  const onFinish = async (values: any) => {
    console.log("登录表单数据:", values);
    setIsLoading(true);
    
    try {
      const res = await request.get("/login", { params: form.getFieldsValue() });
      console.log("登录接口响应:", res.data);
      
      if (res.data.code === 20000) {
        // 使用认证工具保存登录状态
        setLoginStatus(values.phone, res.data.data?.userInfo);
        
        Toast.show({
          icon: 'success',
          content: '登录成功，正在跳转...',
        });
        
        // 登录成功后跳转到首页
        setTimeout(() => {
          navigate('/shouye', { replace: true });
        }, 1500);
      } else {
        // 登录失败
        Toast.show({
          icon: 'fail',
          content: res.data.message || '登录失败，请检查手机号和验证码',
        });
      }
    } catch (error) {
      console.error("登录请求失败:", error);
      Toast.show({
        icon: 'fail',
        content: '网络错误，请重试',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const sendCode = async () => {
    const phone = form.getFieldValue("phone");
    if (!phone) {
      Toast.show({
        icon: 'fail',
        content: '请先输入手机号',
      });
      return;
    }

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      Toast.show({
        icon: 'fail',
        content: '请输入正确的手机号格式',
      });
      return;
    }

    if (countdown > 0) return;

    try {
      // console.log(phone)
      const res = await request.post("/login", { phone });
      console.log("发送验证码响应:", res.data);
      
      if (res.data.code === 20000) {
        // 自动填充验证码到输入框
        const verificationCode = res.data.data;
        form.setFieldValue("code", verificationCode);
        
        Toast.show({
          icon: 'success',
          content: `验证码已发送: ${verificationCode}`,
        });
        
        // 开始倒计时
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        Toast.show({
          icon: 'fail',
          content: res.data.message || '发送验证码失败',
        });
      }
    } catch (error) {
      console.log('aaaaaa')
      console.error("发送验证码失败:", error);
      Toast.show({
        icon: 'fail',
        content: '网络错误，请重试',
      });
    }
  };

  // 快速填充测试数据（开发环境使用）
  const fillTestData = () => {
    form.setFieldValue("phone", "13800138000");
  };

  return (
    <div className="login-container">
      <div className="login-background">
        <div className="login-bg-circle circle-1"></div>
        <div className="login-bg-circle circle-2"></div>
        <div className="login-bg-circle circle-3"></div>
      </div>
      
      <div className="login-content">
        <div className="login-header">
          <div className="login-logo">
            <div className="logo-icon">🏥</div>
            <h1 className="login-title">妙手医生</h1>
            <p className="login-subtitle">专业医疗服务平台</p>
          </div>
        </div>

        <div className="login-card">
          <div className="card-header">
            <h2>欢迎登录</h2>
            <p>请输入您的手机号和验证码</p>
          </div>

          <Form
            form={form}
            layout="vertical"
            onFinish={onFinish}
            className="login-form"
          >
            <Form.Item
              label="手机号"
              name="phone"
              rules={[
                { required: true, message: "请输入您的手机号码!" },
                { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码!" }
              ]}
            >
              <Input 
                placeholder="请输入手机号" 
                className="custom-input"
                prefix={<span className="input-icon">📱</span>}
              />
            </Form.Item>
            
            <Form.Item
              label="验证码"
              name="code"
              rules={[{ required: true, message: "请输入验证码!" }]}
            >
              <div className="code-input-group">
                <Input 
                  placeholder="请输入验证码" 
                  className="custom-input code-input"
                  prefix={<span className="input-icon">🔐</span>}
                />
                <Button
                  className={`send-code-btn ${countdown > 0 ? 'disabled' : ''}`}
                  onClick={sendCode}
                  disabled={countdown > 0}
                >
                  {countdown > 0 ? `${countdown}s` : '发送验证码'}
                </Button>
              </div>
            </Form.Item>

            <Form.Item className="submit-item">
              <Button 
                block 
                type="submit" 
                color="primary" 
                size="large"
                className="login-btn"
                loading={isLoading}
              >
                {isLoading ? '登录中...' : '立即登录'}
              </Button>
            </Form.Item>
          </Form>

          {/* 开发环境快速填充按钮 */}
          {process.env.NODE_ENV === 'development' && (
            <div style={{ textAlign: 'center', marginTop: '10px' }}>
              <Button 
                size="small" 
                fill="outline" 
                onClick={fillTestData}
                style={{ fontSize: '12px', color: '#999' }}
              >
                填充测试数据
              </Button>
            </div>
          )}

          <div className="login-footer">
            <p>登录即表示同意 <a href="#">用户协议</a> 和 <a href="#">隐私政策</a></p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Index;
